package com.server.questionbank.snframe.util.MinIo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.concurrent.TimeUnit;

public class ProgressInputStream extends FilterInputStream {
    private long totalBytes;
    private long bytesRead;
    private ProgressListener progressListener;
    private final StringRedisTemplate redisTemplate;
    private String sessionId;

    public ProgressInputStream(InputStream in, long totalBytes, ProgressListener progressListener, String sessionId, StringRedisTemplate redisTemplate) {
        super(in);
        this.totalBytes = totalBytes;
        this.bytesRead = 0;
        this.progressListener = progressListener;
        this.sessionId = sessionId;
        this.redisTemplate = redisTemplate;
    }

    @Override
    public int read() throws IOException {
        int byteData = super.read();
        if (byteData != -1) {
            bytesRead++;
            updateProgress();
        }
        return byteData;
    }

    @Override
    public int read(byte[] b, int off, int len) throws IOException {
        int bytesReadNow = super.read(b, off, len);
        if (bytesReadNow != -1) {
            bytesRead += bytesReadNow;
            updateProgress();
        }
        return bytesReadNow;
    }

    private void updateProgress() {
        float progress = (float) ((bytesRead * 100.0) / totalBytes);
        progressListener.onProgress(progress);
        redisTemplate.opsForValue().set("download_upload_progress_" + sessionId, String.valueOf(progress),  10, TimeUnit.MINUTES);
    }

    public interface ProgressListener {
        void onProgress(float progress);
    }

    public static float getProgress(StringRedisTemplate redisTemplate, String sessionId) {
        String value = redisTemplate.opsForValue().get("download_upload_progress_" + sessionId);
        float progress = value != null ? Float.parseFloat(value) : 0;
        if (progress >= 100) redisTemplate.delete("download_upload_progress_" + sessionId);
        return progress;
    }
}
